<template>
  <div class="setting-product flex-y" v-loading="loading" >
    <div class="setting-product-header">
      <div class="flex-1">
        <span v-if="!pageButtonSetGray">{{$t('common.form.setting.setCustomField')}}</span>
        <div class="flex-x flex-1 jus-center setting-header-box" v-if="pageButtonSetGray">
          <div class="setting-header-item-box" :class="[nowType === 'form' ? 'is-checked' : '']" @click="nowType = 'form'">{{ $t('projectManage.setting.workLog.tip5') }}</div>
          <div class="setting-header-item-box" :class="[nowType === 'button' ? 'is-checked' : '']" @click="nowType = 'button'">{{ $t('setting.buttonSet.text1') }}</div>
        </div>
      </div>
      <base-button type="primary" native-type="submit" :disabled="pending" @event="confirm">{{$t('common.base.save')}}</base-button>
    </div>
    <div class="setting-product-design" v-show="nowType === 'form'">
      <form-design 
        v-model="fields" 
        :max="maxField" 
        mode="product" 
        :isOpenRegister="isOpenRegister"
        :templateId="templateId"
        :templateName="templateName"
      >
      </form-design>
    </div>
    <div class="flex-1" v-show="nowType === 'button'">
      <ButtonSet ref="buttonSetDom" v-if="pageButtonSetGray" :mode="ButtonGetTriggerModuleEnum.Product"></ButtonSet>
    </div>
  </div>
</template>

<script>
import * as FormUtil from '@src/component/form/util';
import http from '@src/util/http';
import platform from '@src/platform';
import ButtonSet from '@src/component/compomentV2/buttonSet/index.vue';

/* api */
import { getProductFieldsV2, productSaveFields } from '@src/api/ProductApi';
import {
  getMapping,
  getProductMenu,
  getConfig
} from '@src/api/ProductV2Api';

/* mixin */
import fieldMixin from '@src/mixins/fieldMixin';
import FormDesignMixin from '@src/mixins/formDesign';
import ThemeMixin from '@src/mixins/themeMixin/index.ts'
/* model */
import { ConnectorBizTypeIdEnum } from '@src/modules/connector/model'

import { ButtonGetTriggerModuleEnum } from 'pub-bbx-global/pageType/dist/enum/ButtonSetEnum';
import { packToHttpByHttpDataForButonList, packToLocalByHttpDataForButonList } from '@src/component/compomentV2/buttonSet/common';
import { setDataForButtonSet, getDataForButtonSet } from '@src/api/SystemApi';
import { havePageButtonSetGray } from '@src/util/grayInfo';


export default {
  name: 'setting-product-fields-view',
  mixins: [fieldMixin, FormDesignMixin, ThemeMixin],
  props: {
    initData: {
      type: Object,
      default: () => ({})
    }
  },
  data(){
    return {
      loading: true,
      excludeFormType: ['separator', 'email', 'phone', 'radio'],
      fields: [],
      hideFields: [], // 需要隐藏并且提交时需要传给后端的字段
      pending: false,
      maxField: this.initData.fieldNum,
      isOpenRegister: false,
      productMenuOptions: {
        value: []
      },
      nowType: 'form',
      ButtonGetTriggerModuleEnum,
      pageButtonSetGray:havePageButtonSetGray(),
    }
  },
  components: {
    ButtonSet,
  },
  provide() {
    return {
      productMenuOptions: this.productMenuOptions
    }
  },
  computed: {
    templateId() {
      return ConnectorBizTypeIdEnum.Product
    },
    templateName() {
      return this.$t('common.connector.productForm')
    }
  },
  mounted(){
    this.initRefreshProduct()
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeHandler);
  },
  methods: {
    // 初始化刷新产品表单数据
    initRefreshProduct() { 
      this.getFieldsInfoReq()
      this.isOpenRegisterCheck()
      !this.initData.openSuperCodePro && this.getProductMenu()
      if(this.pageButtonSetGray){
        this.getButtonSetData()
      }
    },
    // 获取产品类型选项
    async getProductMenu() {
      let res = await getProductMenu()
      if (res.code === 0) {
        let data = res.result || []
        data.forEach(v => {
          v.value = v.catalogName
          v.idKey = v.id + ''
        })
        this.productMenuOptions.value = data
      }
    },
    back(){
      window.parent.frameHistoryBack(window)
    },
    resizeHandler(event) {
      this.computedFormWidthAndHeight('setting-product');
    },
    async submit(){
      try {
        // 合并隐藏的自定义字段数据
        this.fields = this.fields.concat(this.hideFields)
        let fields = FormUtil.toField(this.fields);
        
        let mappingCheck = true
        fields.forEach(item => {
          item.tableName = 'product';
          if(item.fieldName == 'serialNumber' && item.isSystem) {
            item.setting.serialNumberUnique = (item.setting.serialNumberUnique === true);
          }
          if(!item.isHidden && (!!item.fieldMappingForm?.sourceField ^ !!item.fieldMappingForm?.sourceTable)) {

            mappingCheck = false
          }
          if(!this.initData.openSuperCodePro && item.fieldName === 'catalogId') {
            let catalogs = this.productMenuOptions.value || []
            catalogs.forEach(v => {
              v.catalogName = v.value
              v.id = v.idKey.includes('temporary_value_') ? '' : v.idKey
            })
            item.catalogs = catalogs.filter(v => v.catalogName)
          }
          // 这里对产品地址表单做存储强转
          if (item.fieldName === 'productCompleteAddress') {
            item.formType = 'address';
          }

          // 服务商表单
          if (item.fieldName === 'serviceProviders') {
            (item.subFormFieldList || []).forEach((item, index)  => {
              item.orderId = index;
            })
          }

          // 产品数据来源配置
          item.fieldMappingForm = !item.fieldMappingForm?.sourceField && !item.fieldMappingForm?.sourceTable ? null : item.fieldMappingForm;
        });
        if(!mappingCheck) {
          platform.notification({
            type: 'warning',
            title: this.$t('common.base.toast'),
            message: this.$t('settingProduct.fieldsMessage.warning')
          })
          return
        }

        let message = FormUtil.validate(fields);
        if(!FormUtil.notification(message, this.$createElement)) return;

        this.pending = true;
     
        const result = await productSaveFields(fields);
        if(result.success){
          platform.notification({
            type: 'success',
            title: this.$t('common.base.success'),
            message: this.$t('settingProduct.fieldsMessage.success')
          })
          this.initRefreshProduct()
          return;
        }

        platform.notification({
          type: 'error',
          title: this.$t('settingProduct.fieldsMessage.error'),
          message: result.message
        })
      } catch (error) {
        console.error(error)
      } finally {
        this.pending = false;
      }
    },
    // 获取产品表单属性列表
    getFieldsInfoReq() {
      this.loading = true;
      getProductFieldsV2({isFromSetting:true}).then((res)=>{
        const { status, data, message } = res;
        if( status == 0){
          const fields = data || [];
          const sortedFields = fields.sort((a, b) => a.orderId - b.orderId);
          this.fields = FormUtil.toFormField(sortedFields);
          this.hideFields = []
          this.fields.forEach(f => {
            if (f.setting && f.setting.isEdit == 0) {
              // 保存隐藏的自定义字段
              this.hideFields.push(f)
            }else if (f.fieldName === 'productCompleteAddress') {
              // 这里对产品地址表单做解析强转
              f.formType = 'productCompleteAddress';
            }
          })
          // 过滤不能编辑的自定义字段 不展示（是否重复报修）
          this.fields = this.fields.filter(field => field.setting?.isEdit != 0)
        }

        this.loading = false;
        return getMapping({
          destTable:'product',
          sourceTable:'register'
        })
      }).then(r=>{
        if(r.status == 0){
          for(let item of this.fields){
            r.data.forEach(i=>{
              if(item.fieldName == i.destFieldName){
                item.fieldMappingForm = {
                  'sourceTable': 'register',
                  'sourceField': i.sourceFieldName,
                  'sourceFieldDisplayName': i.sourceFieldDisplayName,
                  'registerFieldFlag': i.registerFieldFlag
                }
              }
            })
          }
        }
      }).catch(error=>{
        this.loading = false;
      }).finally(()=>{
        this.loading = false;
      })
    },

    isOpenRegisterCheck() {
      getConfig({
        configCode: [
          'PRODUCT_REGISTRATION'
        ]
      }).then(res => {
        if(res.errorCode === 0) {
          console.log(res?.data[0]?.isOpen)
          this.isOpenRegister = !!res?.data[0]?.isOpen
        }
      })
    },
    async confirm() {
      if (this.nowType === 'button') {
        const value = await this.$refs.buttonSetDom.getValue();
        if(!value) return
        this.pending = true;
        const btnList = packToHttpByHttpDataForButonList(value);
        setDataForButtonSet({
          module: ButtonGetTriggerModuleEnum.Product,
          buttonList: btnList,
          moduleId:2,
        }).then(res => {
          if (res.status === 0) {
            platform.notification({
              type: 'success',
              title: this.$t('common.base.success'),
              message: this.$t('common.modal.MODIFY_SUCCESS')
            })
            return this.getButtonSetData();
          } else {
            platform.notification({
              type: 'error',
              title: this.$t('common.base.moduleFieldUpdateError', { module: this.$t('common.form.type.customer') }),
              message: res.message,
            });
          }
        }).finally(()=>{
          this.pending = false;
        });
      } else {
        this.submit();
      }
    },
    getButtonSetData() {
      getDataForButtonSet({
        module: ButtonGetTriggerModuleEnum.Product,
        moduleId: 2,
        showArea: 'list',
        isEdit: true,
      }).then(res => {
        if (res.status === 0) {
          const arr = packToLocalByHttpDataForButonList(res.data);
          this.$refs.buttonSetDom.initArr(arr);
        }
      });
    },
  },
}
</script>

<style lang="scss">
html,body{
  height: 100%;
}
.setting-product{
  height: 100%;
  overflow-y: hidden;
}

.setting-header-text{
  margin-right: 12px;
}

.setting-product-header{
  margin: 12px 12px 0 12px;
  padding: 10px;
  display: flex;
  flex-flow: row nowrap;
  align-items: center;
  justify-content: space-between;
  background-color: #fff;
  border-bottom: 1px solid #f4f7f5;
}

.setting-product-design{
  padding: 12px;
  height: calc(100% - 53px);
}

.setting-back-btn{
  i.iconfont{
    line-height: 12px;
    font-size: 12px;
  }
}

</style>
<style lang="scss" scoped>
@import '@src/modules/setting/customer/chooseType.scss'
</style>
